package org.ogv.usada.views;

import org.ogv.OGV;
import org.ogv.usada.models.GP;

import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;

public class HowTo {
	private boolean 		_backTouched;
	private TextureRegion[] _pages;
	private int				_activePage;
	private Sprite			_btnR, _btnL, _btnExit;
	
	public HowTo(String[][] pagePaths) {
		//Initialize pages
		_pages = new TextureRegion[pagePaths.length];
		for(int i = 0; i < _pages.length; ++i) {
			_pages[i] = OGV.asset.getTextureRegion(pagePaths[i]);
		}
		_activePage = 0;
		
		//Initialize touch areas
		float margin = 60;
		_btnR			= new Sprite(OGV.asset.getTextureRegion(GP.$().RES_TEXR_HOWTO_BTN_R));
		_btnR.setPosition(GP.$().GAME_WIDTH - _btnR.getWidth() - margin, (GP.$().GAME_HEIGHT - _btnR.getHeight()) / 2);
		_btnL			= new Sprite(OGV.asset.getTextureRegion(GP.$().RES_TEXR_HOWTO_BTN_L));
		_btnL.setPosition(margin, (GP.$().GAME_HEIGHT - _btnL.getHeight()) / 2);
		_btnExit		= new Sprite(OGV.asset.getTextureRegion(GP.$().RES_TEXR_OPT_EXIT));
		_btnExit.setPosition(GP.$().GAME_WIDTH - _btnExit.getWidth() - margin, margin);
	}

	public void draw(SpriteBatch sb) {
		sb.draw(_pages[_activePage], 0, 0);
		if(_activePage < _pages.length - 1) _btnR.draw(sb);
		if(_activePage > 0) _btnL.draw(sb);
		_btnExit.draw(sb);
	}

	public boolean backTouched() {
		boolean ret = _backTouched;
		_backTouched = false;
		return ret;
	}

	public void update(float elapsedTime, boolean touched, float x, float y) {
		if(!touched) return;
		
		if(swipeRight(x,y))
			nextPage();
		else if(swipeLeft(x,y))
			prevPage();
		else if(exit(x,y))
			_backTouched = true;
			
	}

	private boolean exit(float x, float y) {
		return _btnExit.getBoundingRectangle().contains(x, y);
	}

	private void prevPage() {
		--_activePage;
		validatePage();
	}

	private boolean swipeLeft(float x, float y) {
		return _btnL.getBoundingRectangle().contains(x, y);
	}

	private void nextPage() {
		++_activePage;
		validatePage();
	}

	private void validatePage() {
		_activePage = Math.max(0, Math.min(_activePage, _pages.length-1));
	}

	private boolean swipeRight(float x, float y) {
		return _btnR.getBoundingRectangle().contains(x, y);
	}

}
